/**
 * 
 */
package com.ly.hotel.view.fragments.vod;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.model.Episodepart;
import com.ly.hotel.model.VodVideoBean;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.util.HttpDownloader;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.common.BaseActivity;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.StringReader;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author jouson 2015-1-10
 */
public class EpisodeDetailActivity extends BaseActivity {

	private static final String TAG = "EpisodeDetailActivity";
	// 电影类别的名字列表Adapter

	// 电影分类的名字在这里
	private List<Episodepart> episodeList = new ArrayList<>();
	
	private List<List<Vodvideo>> lEpList = new ArrayList<>();
	
	private int typePosition;

	//电视剧海报view
	private ImageView posterView;
	
	//电视左滑View
	private ImageView toLeftView;
		
	//电视右滑view
	private ImageView toRightView;
	
	//电视剧集文字view
	private TextView countView;
	
	//电视剧类型view
	private TextView genreView;
	
	//电视剧主演view
	private TextView starringView;
	
	//电视剧主演view
	private TextView overviewView;
	
	private ViewPager mViewPager;
	
	//剧集导航栏
	private LinearLayout viewPageTool;
	
	private MyApplication app;
	
	// 剧集列表List
	private ArrayList<Vodvideo> gridviewList = new ArrayList<>();;
	private ThisHandler handlerMsg = new ThisHandler(this);
	public Vodvideo video;

	public static final int INIT_INTRO =  1;

	public static void actionStart(Context context,String title,int pos){
		Intent intent = new Intent(context,EpisodeDetailActivity.class);
		intent.putExtra("title", title);
		intent.putExtra("position", pos);
		context.startActivity(intent);
	}
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_episodedetail);
		
		app = (MyApplication) getApplicationContext();
		app.vodsList.clear();
		Intent intent = this.getIntent();
        typePosition = intent.getIntExtra("position", 0);
        String name = intent.getStringExtra("title");		
		TextView title = findViewById(R.id.act_title).findViewById(R.id.activity_name);
		TextView titleText = findViewById(R.id.name_text);
		title.setText(name);
		titleText.setText(name);
		findView();	
		initView();
		setListener();
	}
	
	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy");
	}
	
	@Override
	public void finish() {
		super.finish();
	}
	

	@Override
	public void onPause() {
		super.onPause();
	}

	private void findView() {	
		posterView = findViewById(R.id.poster_img);
		countView = findViewById(R.id.count_text);
		genreView = findViewById(R.id.genre_text);
		starringView = findViewById(R.id.starring_text);
		overviewView = findViewById(R.id.overview_text);
		mViewPager = findViewById(R.id.episodes_viewpager);
		toLeftView = findViewById(R.id.left_more);
		toRightView = findViewById(R.id.right_more);
		viewPageTool = findViewById(R.id.episodes_tool);
	}
	
	
	private void initView(){
		List<Episodepart> appEpisode = MyApplication.getVodEpisode();
		if (appEpisode != null && !appEpisode.isEmpty()) {
			if (appEpisode.size() > 0) {
				// 清掉再加
				episodeList.clear();
				episodeList.addAll(appEpisode);
				
				if(episodeList.size() >= 1){	
					Episodepart ep = episodeList.get(typePosition);
					String tmp[] = MyApplication.getHostIp().split(":");
					String imgPath = "";
					String introPath = "";
					@SuppressWarnings("deprecation")
					String encodeP = URLEncoder.encode(ep.getIntroPath()).replaceAll("\\+","%20").replaceAll("%2F","/");
					if(tmp.length == 2 && !ep.getServerPort().equals("0")){
						imgPath = "http://" + tmp[0] + ":" + ep.getServerPort() + "/" + ep.getPath();
						introPath = "http://" + tmp[0] + ":" + ep.getServerPort() + "/" + encodeP;
					}else{
						imgPath = MyApplication.getHostResUrl() + ep.getPath();
						introPath = MyApplication.getHostResUrl() + encodeP;
					}
					ImageUtil.displayImage(this, imgPath, posterView);
					if(TextUtils.isEmpty(ep.getIntro())){
						loadIntro(introPath,typePosition);
					}else{
						initIntroContent();
					}
					updateVodItemList(ep);
				}
			}
		}else{
			ToastUtil.showShortToast(this, "通讯故障,请返回重试", 3000);
		}
	}
	
	private void updateVodItemList(Episodepart epart) {
		List<VodVideoBean> list;
		/* 根据列表的类型索引获取改索引下的所有视频数据 */
		list = epart.getVodvideoBeanList();
		if (list != null) {
			gridviewList.clear();
			for (VodVideoBean b : list) {
				gridviewList.addAll(b.getMovies());
			}
			Collections.reverse(gridviewList);
			
			int count = gridviewList.size();
			countView.setText("（" + count + " " +getResources().getString(R.string.episode_unit) + "）");
			
			if(gridviewList.size() > 1){
				app.vodsList = gridviewList;
			}
			
			getListIntArray(gridviewList,18);
		}else{
			ToastUtil.showShortToast(this, "通讯错误,请返回重试", 3000);
		}
	}
	
	 @SuppressWarnings("deprecation")
	private void getListIntArray(ArrayList<Vodvideo> v, int s) {
		lEpList.clear();	        
	  	int t = v.size(); 
	  	for (int i = 0; i < t; i = i+s) { 
	    	int fromIndex = i;
	    	int toIndex = i+s;
	      	if(toIndex >= t){
	        	toIndex = t;
	     	}
	     	List<Vodvideo> nv = v.subList(fromIndex, toIndex);
	     	lEpList.add(nv);  
		}
	  	EpisodePagerAdapter mAdapter = new EpisodePagerAdapter(lEpList,this);
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOffscreenPageLimit(10);
		mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.px120));
		if(lEpList.size() > 1){
			viewPageTool.removeAllViews();
			toRightView.setVisibility(View.VISIBLE);
			int marginX = getResources().getDimensionPixelSize(R.dimen.px16);
			int marginY = getResources().getDimensionPixelSize(R.dimen.px6);
			int btnH	= getResources().getDimensionPixelSize(R.dimen.px60);
			for(int i =0 ;i<lEpList.size();i++){
				List<Vodvideo> els = lEpList.get(i);
				int lastp = els.size() - 1;
				String firstName = els.get(0).getName();
				String lastName = els.get(lastp).getName();
				Button tmpBtn = new Button(this);
				tmpBtn.setText(firstName + "—" + lastName);
				tmpBtn.setTextColor(Color.parseColor("#FFFFFF"));
				tmpBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.act_episodes_tool));
				tmpBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.px30));
				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
						btnH);
				layoutParams.setMargins(marginX,marginY,marginX,marginY);
				tmpBtn.setLayoutParams(layoutParams);	
				viewPageTool.addView(tmpBtn);
				final int pos = i;
				tmpBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
					
					@Override
					public void onFocusChange(View arg0, boolean arg1) {
						// TODO Auto-generated method stub
						if(arg1){
							mViewPager.setCurrentItem(pos);
						}
					}
				});
				tmpBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						arg0.requestFocus();
						arg0.requestFocusFromTouch();
					}
				});
				setButtonColor(0);
			}
		}
	}
	 
	private void setListener() {		
		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				int c = lEpList.size();
				if(c > 1){
					if(arg0 == 0){
						toLeftView.setVisibility(View.INVISIBLE);
						toRightView.setVisibility(View.VISIBLE);
					} else if(arg0 + 1 == c){
						toRightView.setVisibility(View.INVISIBLE);
						toLeftView.setVisibility(View.VISIBLE);
					} else {
						toLeftView.setVisibility(View.VISIBLE);
						toRightView.setVisibility(View.VISIBLE);
					}
				}
				setButtonColor(arg0);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		toLeftView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int npos = mViewPager.getCurrentItem();
				if(npos > 0){
					mViewPager.setCurrentItem(npos-1);
				}
			}
		});
		
		toRightView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int npos = mViewPager.getCurrentItem();
				if((npos + 1) < lEpList.size()){
					mViewPager.setCurrentItem(npos+1);
				}
			}
		});
	}
	
	private void loadIntro(final String path,final int pos){
		new Thread() {
			public void run() {
                String content = new HttpDownloader().download(path);
                MyApplication.getVodEpisode().get(pos).setIntro(content);
                handlerMsg.sendEmptyMessage(INIT_INTRO);
			}
		}.start();
	}
	
	//设置背景颜色
	private void setButtonColor(int pos){
		if(viewPageTool.getChildCount()>0){
			for(int i=0;i<viewPageTool.getChildCount();i++){
				if(viewPageTool.getChildAt(i).getClass().getName().contains("Button")){
					Button b = (Button) viewPageTool.getChildAt(i);
					if(i == pos){
						b.setTextColor(Color.parseColor("#00FF7F"));
					}else{
						b.setTextColor(Color.parseColor("#FFFFFF"));
					}
				}
			}
		}
	}
	
	//更新解析介绍内容
	@SuppressWarnings("deprecation")
	private void initIntroContent(){
		String intro = MyApplication.getVodEpisode().get(typePosition).getIntro();
		if(!TextUtils.isEmpty(intro)){
			try{
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				XmlPullParser xmlPullParser = factory.newPullParser();
				xmlPullParser.setInput(new StringReader(intro));
				int eventType = xmlPullParser.getEventType();
				String genre = "";
				String starring = "";
				String overview = "";
				while (eventType != XmlPullParser.END_DOCUMENT){
					String nodeName = xmlPullParser.getName();
					switch (eventType) {
					case XmlPullParser.START_TAG:
						if("type".equals(nodeName)){
							genre = xmlPullParser.nextText();
						} else if("actors".equals(nodeName)){
							starring = xmlPullParser.nextText();
						}else if("intro".equals(nodeName)){
							overview = xmlPullParser.nextText();
						}
						break;
					case XmlPullParser.END_TAG:
						break;
					default:
						break;
					}
					eventType = xmlPullParser.next();
				}
				genreView.setText(URLDecoder.decode(genre));
				starringView.setText(URLDecoder.decode(starring));
				overviewView.setText(URLDecoder.decode(overview));
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	
	/**
	 * handler处理消息机制
	 */
	private static class ThisHandler extends Handler {
		private WeakReference<EpisodeDetailActivity> wrActivity;

		public ThisHandler(EpisodeDetailActivity activity) {
			wrActivity = new WeakReference<EpisodeDetailActivity>(activity);
		}

		@Override
		public void handleMessage(final Message message) {
			final EpisodeDetailActivity act = wrActivity.get();
			Log.i(TAG, "handleMessage="+message.what);
			if (act != null) {
				switch (message.what) {
				case INIT_INTRO:
					act.initIntroContent();
					break;	
				}
			}
		}
	}
}
